/*
 * Copyright 2011 evswork Team
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

package org.evswork.getwit.smackwrap;

import java.util.LinkedList;
import java.util.Queue;

import org.jivesoftware.smack.Chat;

import android.util.Log;


public class SmackMessageSender {
	private SmackWrapper wrapper;

	public final static int RETRY_LIMIT=5;
	private Queue <Data> queue;
	
	class Data {
		String msg;
		int retry;
		
		Data(String msg) {
			this.msg = msg;
			this.retry=0;
		}

		@Override
		public boolean equals(Object o) {
			Data t = (Data)o;
			return t.msg.equals(this.msg);
		}
		
	}
	
	public SmackMessageSender(SmackWrapper w) {
		wrapper = w;
		queue = new LinkedList<Data>();
	}

	private void tryPostAll()
	{
		Chat chat;
		if (!wrapper.tryConnect())
			return;
		Data d=null;
		try {
			chat = wrapper.getChat();
			while (null != (d=queue.poll())) {
				if (d.retry > RETRY_LIMIT) {
					Log.e("Getwit",String.format("msg:[%s],retry limit reached.",d.msg));
					continue;
				}
				chat.sendMessage(d.msg);
				//Log.d("Getwit","new msg sent");
				/*
				for (MessageListener m : chat.getListeners()) {
				
					Log.d("Getwit",m.toString());
				}
				*/
			}
		} catch (Exception e) {
			if (d != null) {
				++d.retry;
				Log.e("Getwit",String.format("%s,when sending [%s],retry=%d", e.toString(),d.msg,d.retry));
				queue.offer(d);
			}
		}
	}
	
	public void post(String msg)
	{
		Data d = new Data(msg);
		if (!queue.contains(d)) {
			queue.offer(d);
		}
		tryPostAll();
	}
	
	public void notifyConnected() {
		tryPostAll();
	}
}
